import { Button, Popconfirm, Space, Table, type TableColumnsType } from "antd";
import { type Key, useCallback, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useRequest } from "ahooks";
import { delRole, getRoleList } from "@/services/role.ts";

import OpDrawer, { type OpDrawerInit } from "./components/op-drawer.tsx";
import AuthButton from "@/components/auth-button";

const SystemRole = () => {
  const { t } = useTranslation();
  const columns: TableColumnsType<API.RoleObject> = [
    { title: "名称", dataIndex: "name" },
    {
      title: "标识",
      dataIndex: "label",
      sorter: (a, b) => (a.label > b.label ? 1 : -1),
    },
    { title: "备注", dataIndex: "remark" },
    { title: "创建时间", dataIndex: "createTime", width: 160 },
    { title: "更新时间", dataIndex: "updateTime", width: 160 },
    {
      title: "操作",
      dataIndex: "remark",
      render: (_, record) => {
        return (
          <Space>
            <Button
              size="small"
              onClick={() => {
                // 打开 OpDrawer 组件，且将当前这一条数据传递给过去
                opDrawerRef.current?.open(record);
              }}
            >
              编辑
            </Button>
            <Popconfirm
              title="提示"
              description="此操作将永久删除选中数据，是否继续？"
              cancelText="取消"
              okText="确认"
              onConfirm={() => {
                // 确认删除
                handleDelete([record.id]);
                // delRole([record.id]).then(() => {
                //   // 从新刷新数据
                //   refresh()
                // })
              }}
            >
              <Button size="small" danger>
                删除
              </Button>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  // const [loading, setLoading] = useState(false);
  // 表格数据源
  // const [data, setData] = useState<API.RoleObject[]>([]);
  // 当前勾选的 selectedRowKeys
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  // 基于 selectedRowKeys 计算删除是否需要禁用
  const deleteBtnDisabled = useMemo<boolean>(() => {
    return !selectedRowKeys.length;
  }, [selectedRowKeys]);

  const [query, setQuery] = useState({
    page: 1,
    size: 10,
  });
  const { data, loading, run, refresh } = useRequest(() => getRoleList(query), {
    // manual: true, // 需要手动调用
    refreshDeps: [query], // 依赖刷新，当依赖项发生变化，会刷新接口调用
  });

  const rowSelectionChange = useCallback(
    (selectedRowKeys: Key[], selectedRows: API.RoleObject[]) => {
      console.log("onChange", selectedRowKeys, selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    []
  );

  const paginationChange = useCallback((page: number, pageSize: number) => {
    console.log("page", page, pageSize);
    // 使用 page, pageSize 修改我们自己的 state 数据
    setQuery((que) => ({ ...que, page: page, size: pageSize }));
  }, []);

  // 删除
  const handleDelete = async (ids?: number[]) => {
    // 如果 ids 为 undefined 就是按照勾选的数据来删除
    if (!ids) {
      await delRole(selectedRowKeys as number[]);
      setSelectedRowKeys([]);
    } else {
      await delRole(ids);
    }
    // 刷新
    refresh();
  };

  // 新增与编辑相关
  //  1. 创建一个 ref 数据，关联 OpDrawer 组件
  const opDrawerRef = useRef<OpDrawerInit>(null);
  //  2. 新增按钮点击
  const handleAdd = () => {
    // 调用 opDrawerRef.current.open()
    opDrawerRef.current?.open();
  };

  return (
    <Space direction="vertical" style={{ display: "flex" }}>
      <Space>
        <Button type="default" onClick={run}>
          {t("buttons.refresh")}
        </Button>
        {/* 按钮权限 */}
        <AuthButton auth="base:sys:role:add">
          <Button type="primary" onClick={handleAdd}>
            {t("buttons.add")}
          </Button>
        </AuthButton>
        <Button
          type="default"
          danger
          disabled={deleteBtnDisabled}
          onClick={() => handleDelete()}
        >
          {t("buttons.del")}
        </Button>
      </Space>

      <Table
        rowKey="id"
        rowSelection={{
          onChange: rowSelectionChange,
        }}
        loading={loading}
        dataSource={data?.list}
        columns={columns}
        scroll={{ y: 300 }}
        pagination={{
          total: data?.pagination.total,
          showSizeChanger: true,
          onChange: paginationChange,
        }}
      />

      <OpDrawer ref={opDrawerRef} onSuccess={refresh} />
    </Space>
  );
};

export default SystemRole;
